<template>
  <div>
    <!--条件-->
      <Row>
          <Col span="24">
              菜单名称  <Input v-model="searchObj.menuName" placeholder="输入菜单名称查询" clearable style="width: 200px" />
              角色名称  <Input v-model="searchObj.roleName" placeholder="输入角色名称查询" clearable style="width: 200px" />
              <DatePicker type="daterange" placement="bottom-end" placeholder="按钮新建时间" style="width: 200px" show-week-numbers></DatePicker>
              <i-button type="success" shape="circle" icon="ios-search" @click="search">查询</i-button>
              <i-button @click="resert()">重置</i-button>
          </Col>
      </Row>

    <!--条件-->
    <Row>
      <Col span="24">
        <i-button type="success" @click="buttonRoleControl()">按钮角色控制</i-button>
        <i-button type="primary" shape="circle" @click="addDig()">新增按钮权限</i-button>
      </Col>
    </Row>

    <div class="home-content">
      <i-table :columns="columns1" :data="data1" @on-selection-change="handleSelectionChange"></i-table>
    </div>
    <Page
      :total="pageData.total"
      :current="pageData.current"
      :page-size="pageData.size"
      show-elevator
      show-total
      @on-change="changePage"
    ></Page>

    <!--新增/修改按钮权限页面-->
    <Modal v-model="operDig" :title="title" @on-cancel="cancel" width="700px">
      <Form :model="buttonObj" :label-width="80" ref="formCustom" :rules="ruleForm">
        <FormItem label="按钮请求地址" prop="url">
          <Input v-model="buttonObj.url" placeholder="权限地址名称,如: blog/save ,不能和已存在重名..." />
        </FormItem>
        <FormItem label="描述">
          <Input v-model="buttonObj.summary" placeholder="对按钮权限进行描述..." />
        </FormItem>

        <FormItem>
          <Row>
            <Col span="10">
              <Tree :data="data5" :render="renderContent" class="demo-tree-render"></Tree>
            </Col>
            <Col span="2">
              <Divider type="vertical" />
            </Col>
            <Col span="12">
              <List :header="menuTitle">
                <ListItem v-for="item in buttonListData" :key="item.id">
                  <ListItemMeta :description="item.url" />
                  <template slot="action">
                    <li v-if="item.id == buttonObj.id">
                      <a @click="removeButton(item.id)">删除</a>
                    </li>
                  </template>
                </ListItem>
              </List>
            </Col>
          </Row>
        </FormItem>
        <FormItem>
          <i-button type="primary" @click="addButton">提交</i-button>
        </FormItem>
      </Form>
    </Modal>

    <Modal v-model="bindRole" title="权限角色绑定" @on-ok="submitBind">
      请选择绑定的角色:
      <Select style="width:400px" multiple >
        <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.roleName" @click.native="changRole(item)"/>
      </Select>
      <div>
        角色名称: {{selectObj.roleName}}
      </div>
      <div>
        角色介绍: {{selectObj.summary}}
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  page,
  changeButton,
  getDetail,
  saveOrUpdate,
  deleteButton,
  buttonList
} from "@/api/buttonPermissionApi";
import { dealPageData } from "@/utils/myPageUtil";
import { Button } from "iview";
import { allMenuIvTree } from "@/api/menuAPi";
import { allRoleList } from "@/api/roleApi";
export default {
  name: "buttonPermission",
  //用于刷新页面
  inject: ["reload"],
  data() {
    return {
      bindRole:false,
      searchObj:{
        menuName:'',
        roleName:''
      },
      roleList:[],
      selectObj:{},
      buttonRoleArr:[],
      operDig: false,
      title: "新增",
      titleArr: [], //用来记录用户选择菜单后,校验是否有重名的,如果有,则提示
      isNew: false, //是否新增加的按钮权限
      checkIdArr: [], //用来校验是否被挂载
      removeId: 0, //当前点击删除的按钮id
      buttonObj: {
        url: "",
        summary: "",
        id: 0,
        menuId: 0
      },
      /*表单校验*/
      ruleForm: {
        url: [{ required: true, message: "角色名称不能为空", trigger: "blur" }]
      },
      columns1: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: "按钮地址",
          key: "url"
        },
        {
          title: "按钮描述",
          key: "summary"
        },
        {
          title: "角色拥有",
          key: "roleName"
        },
        {
          title: "归属菜单",
          key: "menuName"
        },
        {
          title: "状态",
          key: "status",
          render: (h, params) => {
            if (params.row.status == 1) {
              return h("span", "正常");
            } else {
              return h("span", "禁用");
            }
          }
        },
        {
          title: "创建人",
          key: "creator"
        },
        {
          title: "修改人",
          key: "editor"
        },
        {
          title: "创建时间",
          key: "createTime"
        },
        {
          title: "修改时间",
          key: "updateTime"
        },
        {
          title: "操作",
          key: "action",
          width: 150,
          fixed: "right",
          align: "center",
          render: (h, params) => {
            return h("div", [
              //渲染一个div标签
              h(
                Button,
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.editDig(params.row.id);
                    }
                  }
                },
                "编辑"
              ),
              h(
                Button, //在div标签下渲染一个iview组件
                {
                  props: {
                    //传递参数
                    type: "error",
                    size: "small"
                  },
                  style: {
                    //设置样式
                    marginRight: "5px"
                  },
                  on: {
                    //监听$emit事件
                    click: () => {
                      this.changeButton(0, params.row.id);
                    }
                  }
                },
                "禁用按钮权限"
              ),
              h(
                Button,
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.changeButton(1, params.row.id);
                    }
                  }
                },
                "启用按钮权限"
              ),
              h(
                Button,
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data1: [],
      menuTitle: "",
      pageData: {
        total: 0,
        current: 1,
        size: 10,
        data: []
      },
      data5: [],
      buttonListData: [], //按钮数据
      buttonProps: {
        type: "default",
        size: "small"
      }
    };
  },
  methods: {
    submitBind(){
      console.log("buttonRoleArr",this.buttonRoleArr);
      console.log("roleId",this.selectObj.id);





    },
    ok() {},
    cancel() {},
    changRole(value){
      this.selectObj = value;
    },
    handleSelectionChange(val){
      this.buttonRoleArr = [];
      if(val){
        val.forEach(item => {
          this.buttonRoleArr.push(item.id);
        })
      }
    },
    buttonRoleControl(){
      if(!this.buttonRoleArr || this.buttonRoleArr.length == 0){
          this.$Message.error({
            content: '请先选择需要绑定的按钮数据!',
            duration: 3
          });
          return;
      }
      //拉取所有的角色信息
      allRoleList().then(res => {
        if (res.data.code == 200) {
            let data = res.data.data;
            if(data){
              this.roleList = data;
            }
        }
      })
      this.bindRole = true;
    },
    resert(){
      this.searchObj = {};
    },
    search(){
      let obj = {
        current:1,
        size:this.pageData.size
      };
      this.pageFun(obj);
    },
    initPage() {
      let obj = {
        current: this.pageData.current,
        size: this.pageData.size
      };
      this.pageFun(obj);
    },
    pageFun(obj) {
      let searchDate = {
        current:obj.current,
        size:obj.size,
        menuName: this.searchObj.menuName,
        roleName: this.searchObj.roleName
      }
      page(searchDate).then(res => {
        if (res.data.code == 200) {
          //处理分页
          this.pageData = dealPageData(res.data);
          this.data1 = this.pageData.data;
        }
      });
    },
    changeButton(type, id) {
      let obj = {
        id: id,
        type: type
      };
      changeButton(obj).then(res => {
        if (res.data.code == 200) {
          if (type == 0) {
            this.$Message.info("禁用按钮权限成功");
          } else {
            this.$Message.info("启用按钮权限成功");
          }
          this.reload();
        }
      });
    },
    changePage(index) {
       let obj = {
        current: index,
        size: this.pageData.size
      };
      this.pageFun(obj);
    },
    addDig() {
      //清空数据
      this.buttonObj = {};
      this.checkIdArr = [];
      //请求菜单树数据
      allMenuIvTree().then(res => {
        if (res.data.code == 200) {
          console.log("数据", res.data.data);
          this.data5 = res.data.data;
        }
      });
      this.operDig = true;
    },
    addButton() {
      this.$refs.formCustom.validate(valid => {
        if (valid) {
          if (
            this.buttonObj.menuId == undefined ||
            0 == this.buttonObj.menuId
          ) {
            this.$Notice.error({
              title: "错误提示^-^",
              desc: "请绑定菜单页面"
            });
            return;
          }
          console.log("提交的数据", this.buttonObj);
          saveOrUpdate(this.buttonObj).then(res => {
            if (res.data.code == 200) {
              if (this.buttonObj.id != 0) {
                this.$Notice.success({
                  desc: "编辑成功"
                });
              } else {
                this.$Notice.error({
                  desc: "新增成功"
                });
              }
              this.reload();
            }
          });
        }
      });
    },
    editDig(id) {
      //查询详情
      this.title = "编辑";
      this.buttonObj.id = id;
      getDetail(id).then(res => {
        if (res.data.code == 200) {
          this.buttonObj = res.data.data;
          this.checkIdArr.push(this.buttonObj.id);
        }
      });
      //请求菜单树数据
      allMenuIvTree().then(res => {
        if (res.data.code == 200) {
          console.log("数据", res.data.data);
          this.data5 = res.data.data;
        }
      });
      this.operDig = true;
    },
    remove(id) {
      deleteButton(id).then(res => {
        if (res.data.code == 200) {
          this.$Message.info("删除成功");
          this.reload();
        }
      });
    },
    renderContent(h, { root, node, data }) {
      return h(
        "span",
        {
          style: {
            display: "inline-block",
            width: "100%"
          }
        },
        [
          h("span", [
            h("Icon", {
              props: {
                type: "ios-paper-outline"
              },
              style: {
                marginRight: "8px"
              }
            }),
            h("span", data.title)
          ]),
          h(
            "span",
            {
              style: {
                display: "inline-block",
                float: "right",
                marginRight: "32px"
              }
            },
            [
              h("Button", {
                props: Object.assign({}, this.buttonProps, {
                  icon: "md-eye"
                }),
                style: {
                  marginRight: "8px",
                  display:
                    !node.children || node.children.length <= 0
                      ? "inline-block"
                      : "none"
                },
                on: {
                  click: () => {
                    this.showButtonList(data);
                  }
                }
              }),
              h("Button", {
                props: Object.assign({}, this.buttonProps, {
                  icon: "ios-add"
                }),
                style: {
                  marginRight: "8px",
                  display:
                    !node.children || node.children.length <= 0
                      ? "inline-block"
                      : "none"
                },
                on: {
                  click: () => {
                    this.append(data, node, root);
                  }
                }
              })
            ]
          )
        ]
      );
    },
    append(data, node, root) {
      if (this.buttonObj.url == undefined || this.buttonObj.url == "") {
        this.$Message.error("请先填写url地址");
        return;
      }
      //校验是否被挂载
      if (this.checkButton()) {
        this.$Message.error("请先解除再进行绑定");
        return;
      }
      //当前的list添加数据
      this.showButtonList(data);
      //处理需要删除的元素
      if (0 != this.removeId) {
        this.buttonListData = this.buttonListData.filter(
          item => item.id !== this.removeId
        );
      }
      //往当前数组追加数据
      let obj = {
        url: this.buttonObj.url,
        menuId: data.id,
        summary: this.buttonObj.summary,
        id: this.buttonObj.id
      };
      //设置menuId
      this.buttonObj.menuId = data.id;
      this.buttonListData.push(obj);
      this.checkIdArr.push(this.buttonObj.id);
      console.log("bbubu", this.buttonListData);
    },
    showButtonList(data) {
      //先清空数据
      this.buttonListData = [];
      let menuId = 0;
      if (data.length != 0) {
        //当前选择的节点的菜单id
        const menuId = data.id;
        this.menuTitle = data.title;
        //查询当前菜单挂载的按钮权限
        const obj = {
          menuId: menuId
        };
        buttonList(obj).then(res => {
          if (res.data.code == 200) {
            res.data.data.forEach(item => {
              this.buttonListData.push(item);
            });
          }
        });
        this.$Message.info("選擇");
      }
    },
    removeButton(id) {
      let arr = this.buttonListData.filter(item => item.id !== id);
      this.buttonListData = arr;
      //删除menuId
      this.buttonObj.menuId = 0;
      this.removeId = id;
      console.log("be", this.buttonListData);
      this.checkIdArr = [];
      this.checkIdArr = this.checkIdArr.filter(item => item.id !== id);
      console.log("remove", this.checkIdArr);
    },
    checkButton() {
      //用来校验按钮是否已经被挂载到菜单上了
      if (this.checkIdArr.length > 0) {
        return true;
      } else {
        return false;
      }
    }
  },
  created() {
    this.initPage();
  },
  watch: {
    buttonListData: {
      handler(newVal, oldVal) {
        this.buttonListData = newVal;
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.demo-tree-render .ivu-tree-title {
  width: 100%;
}
</style>
